import { searchStudents } from '../services/student'
import { routerRedux } from 'dva/router'
export default {
    state: {
        condition: {
            key: "",
            sex: -1,
            page: 1,
            limit: 10
        },
        result: {
            total: 0,
            datas: []
        }
    },
    subscriptions: {
        listenUrl({ history, dispatch }) {
            // 初始化加载数据
            dispatch({ type: "fetchStudents" })
            // 监听地址变化
            history.listen(newLocation => {
                if (newLocation.pathname != '/student') return
                // 改变地址更新到仓库 
                dispatch({ type: "changeCondition", payload: newLocation.query })
                // 重新查询
                dispatch({ type: "fetchStudents" })
            })
        }
    },
    reducers: {
        changeCondition(state, { payload }) {
            return { ...state, condition: { ...state.condition, ...payload } }
        },
        setResult(state, { payload }) {
            return { ...state, result: payload }
        }
    },
    effects: {
        *fetchStudents(action, { put, call, select }) {
            // yield put({ type: 'changeCondition', payload: action.payload })
            const condition = yield select(state => state.students.condition)
            const result = yield call(searchStudents, condition)
            yield put({ type: 'setResult', payload: result })
        },
        *setCondition(action, { put, select }) {
            let condition = yield select(state => state.students.condition)
            condition = { ...condition, ...action.payload }
            const params = Object.entries(condition).map(([key, value]) => value !== "" ? `${key}=${value}` : "").filter(s => s)
            yield put(routerRedux.push(`?${params.join("&")}`)) // 构建地址栏参数
        }
    }
}